#!/bin/bash

# get-institution-from-domain.sh < domain.txt
#
# Script that reads from the standard input a list of domains,
# finds the "Registered for:" field in the whois for a domain, and
# gives the corresponding list in the standard output.
#
# v0.3  30 Aug 2007
#
# Author: Ramon Casero <ramon.casero@oucs.ox.ac.uk>
# Copyright © 2007 University of Oxford
#
# This file is part of mta-tracker.
#
# mta-tracker is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mta-tracker is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mta-tracker.  If not, see <http://www.gnu.org/licenses/>.
#
# ChangeLog
#
# * 2008-08-21 (rcasero):
#
#   ** Upgrade licence to GPL v3.
#
# * 2007-08-30 (rcasero): v0.3.
#
#   ** Search for "Registered For:" or "Registered for:" in the whois.
#
# * 2007-08-28 (rcasero): v0.2.
#
#   ** Remove closing whitespace
#
# * 2007-06-27 (rcasero): v0.1. First running version.

while read domain
  do

  # remove trailing tab, turn to lowercase, remove punctuation
  # signs, remove duplicated blanks, remove closing whitespace
  s="`whois $domain | egrep -A 1 'Registered [Ff]or:' | tail -n 1 \
        | tr -d "\t" | tr [:upper:] [:lower:] | tr -d [:punct:] \
        | tr -s " " | sed 's/[ ]$//' `"

  # remove trailing "the", if any
  case "$s" in
      the\ *)
      s="${s:4}"
      ;;
  esac

  # not registered domains
  if [[ "$s" == "" ]]; then
      s="not registered"
  fi

  # output and remove non-printable characters
  # this is necessary because some institutions have non-ASCII
  # characters in the whois, that appear as non-printable characters in
  # the log
  echo "$s" | tr -cd '[[:print:]\t\n]'

done
